//react-router:实现了路由的核心功能
//react-router-dom:基于react-router，加入了在浏览器运行环境下的一些功能，例如Link组件、BrowserRouter和HashRouter组件。
// BrowserRouter,HashRouter, Link,MemoryRouter,NavLink,Prompt,Redirect,Route,Router,withRouter
// StaticRouter,Switch,generatePath,matchPath,useHistory,useLocation,useParams,useRouteMatch
//<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
//https://reactrouter.com/web/guides/quick-start

import React from 'react';

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

import RouterConfig from './route-config';

export interface RouterConfg {
  exact?: boolean | undefined;
  path: string;
  component?: any;
  routes?: RouterConfg[];
}

const routes: RouterConfg[] = [];

///路径展开
function normalizePath(configs: RouterConfg[], path: string) {
  configs.forEach((config) => {
    if (!config.path.startsWith('/')) {
      config.path = `${path}/${config.path}`;
    }

    routes.push(config);

    if (config.routes) {
      normalizePath(config.routes, config.path);
    }
  });
}

RouterConfig.forEach((config) => {
  routes.push(config);

  if (config.routes) {
    normalizePath(config.routes, config.path);
  }
});

console.log('展开后的路由', routes);

console.log('原本路由', RouterConfig);

export const renderRouter = function (props: RouterConfg | RouterConfg[]) {
  let routerArr: RouterConfg[] = [];

  if (Array.isArray(props)) {
    routerArr = props;
  } else {
    if (props.routes) {
      routerArr = props.routes;
    }
  }

  if (routerArr.length <= 0) {
    return null;
  }

  return (
    <Switch>
      {routerArr.map((route: any, index: number) => (
        <Route
          exact={route.exact}
          key={index}
          path={route.path}
          render={(props) => <route.component {...props} routers={route} />}
        />
      ))}
    </Switch>
  );
};

function RouterApp() {
  return <Router>{renderRouter(routes)}</Router>;
}

export default RouterApp;
